#!/usr/bin/python
# -*- coding: UTF-8 -*-
from zhihu_oauth import ZhihuClient, ActType, SearchType
from zhihu_oauth.exception import NeedCaptchaException
import pymongo
import os
from config import *
client=pymongo.MongoClient(MONGO_URL);
db=client["zhihu"];
client = ZhihuClient()

def get_location(follwers):
    try:
        result=follwer.locations
        if len(result)>0:
            ll=result[0]
            if ll:
                return ll.name
        else:
            return "未知"
    except Exception as e:
        print(e)
        return "未知"
def get_eductaion(people):
    data=""
    for education in people.educations:
        if 'school' in education:
            data += education.school.name+","
        if 'major' in education:
            data += education.major.name
    return data



def saveToMongo(result):
    try:
        if db["users"].insert(result):
            print("save result success");
    except:
        print("save mongo error")




TOKEN_FILE = 'token.pkl'


client = ZhihuClient()

if os.path.isfile(TOKEN_FILE):
    client.load_token(TOKEN_FILE)
else:
    client.login_in_terminal("fffed","zh441432")
    client.save_token(TOKEN_FILE)

me = client.me()
results=client.search("知乎小管家",SearchType.PEOPLE)


def get_empley(people):
    data=""
    for employment in people.employments:
        if 'company' in employment:
            data += employment.company.name
        if 'job' in employment:
            data += employment.job.name
    return data


def getBusiness(people):
    data=""
    if people.business:
        data = people.business.name
    return data


for result in results:
    column = result.obj
    follwers=column.followers
    for follwer in follwers:
        location=get_location(follwer)
        educations=get_eductaion(follwer)
        employments=get_empley(follwer)
        business=getBusiness(follwer)
        sina_weibo_url=follwer.sina_weibo_url if follwer.is_bind_sina else ""
        people={
            "name":follwer.name,
            "gender":follwer.gender,
            "headline":follwer.headline,
            "location":location,
            "educations":educations,
            "employments":employments,
            "business":business,
            "sina_weibo_url":sina_weibo_url
        }
        print(people)
        saveToMongo(people)


def user_info(url):
    url="https://weibo.cn/1810844963/info"








